package com.thirteenClassicsServer.common;

import com.thirteenClassics.dto.CatalogQueryDTO;
import com.thirteenClassics.dto.CommonDTO;
import com.thirteenClassics.entity.Catalog;
import com.thirteenClassics.entity.CatalogBook;
import com.thirteenClassics.exception.BaseException;
import com.thirteenClassicsServer.cacheService.CatalogBookCacheService;
import com.thirteenClassicsServer.cacheService.UserServiceCache;
import com.thirteenClassicsServer.mapper.CatalogBookMapper;
import com.thirteenClassicsServer.mapper.CatalogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommonService {
    @Autowired
    private CatalogBookMapper catalogBookMapper;
    @Autowired
    private CatalogMapper catalogMapper;
    @Autowired
    private CatalogBookCacheService catalogBookCacheService;

    @Cacheable(value = "JdbCatalogBookByBookAndIndex", key = "'JdbCatalogBookByBookAndIndex-' + #catalogQueryDTO.bookId + '-' + #catalogQueryDTO"
            + ".bookName + '-' + #catalogQueryDTO.index + '-' + #catalogQueryDTO.bookLang")
    public CatalogBook getJdbCatalogBookByBookAndIndex(CatalogQueryDTO catalogQueryDTO){
        List<Catalog> list = catalogMapper.selectCatalogOrdersByName(catalogQueryDTO);
        CommonDTO commonDTO = new CommonDTO();
        commonDTO.setCatalogId(list.get(catalogQueryDTO.getIndex().intValue() - 1).getId());
        commonDTO.setBookId(catalogQueryDTO.getBookId());
        return catalogBookMapper.selectCatalogBookAll(commonDTO);
    }

    @Cacheable(value = "MinorityCatalogBookByBookAndIndex", key = "'MinorityCatalogBookByBookAndIndex-' + #catalogQueryDTO.bookId + '-' + #catalogQueryDTO"
    + ".bookName + '-' + #catalogQueryDTO.index + '-' + #catalogQueryDTO.bookLang")
    public CatalogBook getMinorityCatalogBookByBookAndIndex(CatalogQueryDTO catalogQueryDTO){
        List<Catalog> list = catalogBookCacheService.selectCatalogOrdersByNameAndId(catalogQueryDTO);
        if (list.isEmpty() || catalogQueryDTO.getIndex() < 1 || catalogQueryDTO.getIndex() > list.size()) {
            throw new BaseException("目录信息不存在或索引越界");
        }
        Catalog catalog = list.get((int) (catalogQueryDTO.getIndex() - 1));

        CommonDTO commonDTO = new CommonDTO();
        commonDTO.setCatalogId(catalog.getId());//entryId
        //根据书id和catalogid查到在catalog_book中的记录
        return catalogBookMapper.selectCatalogBookAllMinority(commonDTO);
    }

}
